package com.mlink.ai.chat.utils

import android.app.Activity
import com.google.android.gms.tasks.Task
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManagerFactory
import com.tencent.mmkv.MMKV


object GooglePlayCore {

    const val KEY_NUM_SHOW_REVIEW = "key_num_show_review"

    fun launchGooglePlay(activity: Activity) {
        runCatching {
            val manager = ReviewManagerFactory.create(activity)
            val request: Task<ReviewInfo> = manager.requestReviewFlow()
            request.addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val reviewInfo: ReviewInfo = task.result
                    val flow: Task<Void> = manager.launchReviewFlow(activity, reviewInfo)
                    flow.addOnCompleteListener {
                        // do nothing now
                        val count = MMKV.defaultMMKV().decodeInt(KEY_NUM_SHOW_REVIEW, 0) + 1
                        MMKV.defaultMMKV().encode(KEY_NUM_SHOW_REVIEW, count)
                    }
                } else {
                    // There was some problem, log or handle the error code.
                    //@ReviewErrorCode int reviewErrorCode = ((TaskException) task.getException()).getErrorCode();
                    // do nothing now
                }
            }
        }
    }
}